// redux练习

// 需求:  redux数据 : {c: 8, msg: '123'} , 一个递增,一个递减

// 1.引入createStore
import { createStore, applyMiddleware } from 'redux'
import thunk from 'redux-thunk'

// 2. 定义reducer
function reducer(state = { c: 8, msg: '123' }, action) {
  switch (action.type) {
    case 'inc':
        // action.num 不为undefined时使用action.num 
        // action.num 为undefined的时候使用1
      const value = action.num !== undefined ? action.num : 1
      return {
        ...state,
        c: state.c + value,
      }

    case 'dec':
      return {
        ...state,
        c: state.c - 1,
      }

    default:
      return state
  }
}

// 3. 创建store
const store = createStore(reducer, applyMiddleware(thunk))

// 监听redux数据变化
store.subscribe(() => {
  console.log(store.getState())
})

// 递增
store.dispatch({ type: 'inc', num: 2 })
store.dispatch({ type: 'inc', num: 3 })
store.dispatch({ type: 'inc', num: 0})

// 递减
store.dispatch({ type: 'dec' })
